package net.piggy.config.security.service;

import net.piggy.model.agg.SecurityUser;
import net.piggy.web.mapper.SecurityMapper;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Component
public class PiggyUserDetailsService implements UserDetailsService {

    @Resource
    private SecurityMapper userMapper;

    @Override
    public SecurityUser loadUserByUsername(String username) throws UsernameNotFoundException {
        SecurityUser user = userMapper.findUserByName(username);
        if(user==null) {
            throw new UsernameNotFoundException(username+" not found");
        }
        String authorities = userMapper.findAuthoritiesByName(username);
        List<SimpleGrantedAuthority> authorityList = granted(authorities);
        user.setAuthorities(authorityList);
        String roles = userMapper.findRolesByName(username);
        List<SimpleGrantedAuthority> roleList = granted(roles);
        user.setRoles(roleList);

        return user;
    }

    private List<SimpleGrantedAuthority> granted(String s){
        if(s!=null){
            List<SimpleGrantedAuthority> list = new ArrayList<>();
            String[] strings = s.split(",");
            for (String string : strings) {
                list.add(new SimpleGrantedAuthority(string));
            }
            return list;
        }
        return new ArrayList<>();
    }

}
